import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import BScroll from '@better-scroll/core'
import css from './index.module.scss'
export default class ListScroller extends PureComponent {
    listRef = React.createRef()
    contentRef = React.createRef()

    static propTypes = {
        // 更多配置 可查询better-scroll官网
        // 水平滚动
        scrollX: PropTypes.bool,
        // 垂直滚动
        scrollY: PropTypes.bool,
        onInit: PropTypes.func
    }

    state = {
        bscroll: null
    }

    init = () => {
        const { scrollX, scrollY } = this.props
        if (!this.listRef.current) {
            return
        }
        const bs = new BScroll(this.listRef.current, {
            scrollX: scrollX,
            scrollY: scrollY,
            probeType: 3
        })
        this.setState({
            bscroll: bs
        }, () => {
            typeof this.props.onInit === 'function' && this.props.onInit()
        })
    }

    refresh = () => {
        this.state?.bscroll?.refresh()
    }

    destory = () => {
        if (this.state.bscroll) {
            typeof this.state.bscroll.destory === 'function' && this.state.bscroll.destory()                     
            this.setState({
                bscroll: null
            }) 
        }        
    }

    getContentNode = () => {
        return this.contentRef.current
    }

    scrollToElement = (el, time, offsetX, offsetY) => {
        this.state?.bscroll?.scrollToElement(el, time, offsetX, offsetY)
    }

    componentDidMount() {
        this.init()
    }

    componentDidUpdate() {
        this.refresh()
    }

    componentWillUnmount() {
        this.destory()
    }

    render() {
        const { className, scrollX } = this.props
        return (
            <div className={`${css['wrap']} ${scrollX ? css['wrap-horizontal']: ''} ${className || ''}`} ref={this.listRef}>
                <div className={css["content"]} ref={this.contentRef}>
                    {this.props.children}
                </div>
            </div>
        )
    }
}
